var express = require('express'),
    router = express.Router(),
    tool = require('../utils/common'),
    userModel = require('../db/model/user'),
    borrowModel = require('../db/model/borrow'),
    bookModel = require('../db/model/book');

/**
 * 借阅列表
 */
router.post('/index', (req, res) => {
        (async (req, res) => {
            try {
                let params = req.body, page = 1;
                'page' in params && (page = params.page);
                let auth = await userModel.isLogin(req, res);

                //查询借阅列表
                let model = new borrowModel(), bmodel = new bookModel(),
                    limit = model.getLimit(page),
                    where = {'user_type': auth.user_type, 'user_id': auth.id},
                    borrowList = await model.list(where, limit), bookList = {};
                //循环-查询书籍信息
                for (let index in borrowList) {
                    //解决多次查询的问题，存在的数据不需要再次查询
                    if (!bookList[borrowList[index].book_id]) {
                        let bresult = await bmodel.list({'id': borrowList[index].book_id}, 1);
                        if (bresult && typeof bresult === 'object') {
                            bookList[bresult[0].id] = bresult[0];
                            borrowList[index].book = bresult && bresult.length ? bresult[0] : {};
                        } else borrowList[index].book = {};
                    } else {
                        borrowList[index].book = bookList[borrowList[index].book_id] ? bookList[borrowList[index].book_id] : {};
                    }
                }

                res.json(tool.returnArray({
                    'current_page': page,
                    'last_page': page,
                    'total': 16,
                    'data': borrowList,
                }, 1));
            } catch (e) {
                res.json(tool.errorHandle(e));
            }
        })(req, res);
    }
);

module.exports = router;